<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-row>
        <el-col :span="24">
          <el-form-item label="试题类型" prop="type">
            <el-radio-group v-model="formData.type">
              <el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.EXAM_TEST_TYPE)" :key="dict.value"
                :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="试题题目" prop="title">
            <el-input v-model="formData.title" placeholder="请输入试题题目，仅列表显示" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="试题分类" prop="typeClassification">
            <el-tree-select
v-model="formData.typeClassification" check-on-click-node="true" :data="testTypeList"
              check-strictly :props="{ ...defaultProps, label: 'name' }" multiple default-expand-all placeholder="请选择试题分类"
              clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="题目" prop="question">
            <!-- <el-input v-model="formData.question" placeholder="请输入题目" clearable/> -->
            <Editor
v-model="formData.question" class="w-100%" :height="100" placeholder="请输入题目" :toolbar-config="toolbarConfig"
              clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="题库id" prop="libraryid">
        <el-input v-model="formData.libraryid" placeholder="请输入题库id" clearable/>
      </el-form-item> -->
      <!-- <el-row>
        <el-col :span="8">
          <el-form-item label="试题图片" prop="qimage">
            <UploadImg v-model="formData.qimage" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="试题音频" prop="qaudio">
            <el-input class="mb-5px" v-model="formData.qaudio" placeholder="上传或者输入" clearable />
            <UploadFile v-model="formData.qaudio" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="试题视频" prop="qvideo">
            <el-input class="mb-5px" v-model="formData.qvideo" placeholder="上传或者输入" clearable />
            <UploadFile v-model="formData.qvideo" />
          </el-form-item>
        </el-col>
      </el-row> -->

      <!-- <el-form-item label="选项类型" prop="aType">
        <el-radio-group v-model="formData.aType">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item
v-if="[ExamTestTypeEnum.RADIO, ExamTestTypeEnum.CHECKBOX].includes(formData.type)" label="选项"
        prop="option">
        <div class="flex flex-1 flex-col">
          <div v-for="(item, index) in formData.options" :key="index" class="flex items-center flex-1 mb-10px">
            <div class="mr-2 w-45px flex">
              <el-input v-model="item['key']" /><span>、</span>
            </div>
            <!-- <el-input class="flex-1" v-model="item['value']" placeholder="请输入选项内容" clearable /> -->
            <Editor key="" v-model="item['value']" class="flex-1" :height="60" placeholder="请输入选项内容" :toolbar-config="toolbarConfig" />
            <Icon class="ml-2" icon="ep:remove" :size="30" @click="handleRemoveOption(index)" />
          </div>
          <Icon icon="ep:circle-plus" :size="30" @click="handleAddOption" />
        </div>
      </el-form-item>
      <el-form-item
        v-if="[ExamTestTypeEnum.RADIO, ExamTestTypeEnum.CHECKBOX, ExamTestTypeEnum.JUDGE, ExamTestTypeEnum.FILL_BLANK].includes(formData.type)"
        label="正确答案" prop="rightkey">
        <!-- <el-input v-model="formData.rightkey" placeholder="请输入正确答案" clearable/> -->
        <el-radio-group v-model="formData.rightkey" v-if="ExamTestTypeEnum.RADIO == formData.type">
          <el-radio v-for="(item, index) in formData.options" :key="index" :value="item['value']" :label="item['key']">
            {{ item['key'] }}
          </el-radio>
        </el-radio-group>
        <el-checkbox-group v-model="formData.rightkey" v-if="ExamTestTypeEnum.CHECKBOX == formData.type">
          <el-checkbox
v-for="(item, index) in formData.options" :key="index" :value="item['value']"
            :label="item['key']" />
        </el-checkbox-group>
        <el-radio-group v-model="formData.rightkey" v-if="ExamTestTypeEnum.JUDGE == formData.type">
          <el-radio :value="'A'" :label="'正确'">
            正确
          </el-radio>
          <el-radio :value="'B'" :label="'错误'">
            错误
          </el-radio>
        </el-radio-group>
        <el-input
v-model="formData.rightkey" v-if="ExamTestTypeEnum.FILL_BLANK == formData.type"
          placeholder="请输入答案,多个由【答案1】【答案2】组成" clearable />
      </el-form-item>
      <el-form-item label="答案解析" prop="analysis">
        <!-- <el-input v-model="formData.analysis" placeholder="请输入答案解析" clearable /> -->
        <Editor v-model="formData.analysis" class="w-100%" :height="100" placeholder="请输入答案解析" :toolbar-config="toolbarConfig" />
      </el-form-item>
      <el-form-item label="难度等级" prop="level">
        <el-radio-group v-model="formData.level">
          <el-radio v-for="dict in getIntDictOptions(DICT_TYPE.EXAM_TEST_LEVEL)" :key="dict.value" :label="dict.value">
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-row>
        <el-col :span="8">
          <el-form-item label="解析图片" prop="aimage">
            <UploadImg v-model="formData.aimage" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="解析音频" prop="analysisAudio">
            <el-input class="mb-5px" v-model="formData.analysisAudio" placeholder="上传或者输入" clearable />
            <UploadFile v-model="formData.analysisAudio" :fileType="['mp3', 'wav']" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="解析视频" prop="analysisVideo">
            <el-input class="mb-5px" v-model="formData.analysisVideo" placeholder="上传或者输入" clearable />
            <UploadFile v-model="formData.analysisVideo" :fileType="['mp4', 'avi',]" />
          </el-form-item>
        </el-col>
      </el-row> -->

      <!-- <el-form-item label="本题答题次数" prop="anum">
        <el-input v-model="formData.anum" placeholder="请输入本题答题次数 仅考试" clearable/>
      </el-form-item>
      <el-form-item label="正确回答次数" prop="rnum">
        <el-input v-model="formData.rnum" placeholder="请输入正确回答次数 仅考试" clearable/>
      </el-form-item> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="知识点分类" prop="knowledge">
            <!-- <el-input v-model="formData.knowledge" placeholder="请输入所属知识点类别" clearable /> -->
            <el-tree-select
              v-model="formData.knowledge"
              :data="knowledgeCateTree"
              :props="defaultProps"
              check-strictly
              default-expand-all
              placeholder="请选择所属知识点类别" clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年份" prop="qYear">
            <el-input v-model="formData.qYear" placeholder="请输入年份" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="问题父id" prop="pid">
        <el-input v-model="formData.pid" placeholder="请输入问题父id" clearable/>
      </el-form-item> -->
      <el-row>
        <el-col :span="12">
          <el-form-item label="语音小题" prop="sonStatus">
            <el-radio-group v-model="formData.sonStatus">
              <el-radio
v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)" :key="dict.value"
                :label="dict.value">
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="语音示例" prop="sonSimple">
            <UploadFile v-model="formData.sonSimple" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { TestApi, TestVO } from '@/api/exam/test'
import { TestTypeApi, TestTypeVO } from '@/api/exam/testtype'
import { handleTree, defaultProps } from '@/utils/tree'
import { ExamTestTypeEnum } from '@/utils/constants'
import { knowledgeCateTree } from '../knowledge/knowledge.data'
import { cloneDeep } from 'lodash-es'
const toolbarConfig = {
  toolbarKeys: [
  'bold', // 粗体
  'italic', // 斜体
  'underline', // 下划线
  'uploadImage',
  'uploadVideo',
  'kityFormula'
  ]
}
/** 题库 表单 */
defineOptions({ name: 'TestForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
//索引转字母
const indexToLetter = (index: number) => {
  return String.fromCharCode(65 + index);
}
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  type: undefined,
  title: undefined,
  libraryid: undefined,
  question: undefined,
  qimage: undefined,
  qaudio: undefined,
  aType: undefined,
  options: [{ key: indexToLetter(0), value: '' }],
  rightkey: undefined,
  analysis: undefined,
  aimage: undefined,
  anum: undefined,
  rnum: undefined,
  level: undefined,
  qvideo: undefined,
  analysisAudio: undefined,
  analysisVideo: undefined,
  knowledge: undefined,
  typeClassification: [],
  qYear: undefined,
  pid: undefined,
  sonStatus: undefined,
  sonSimple: undefined
})
const formRules = reactive({
  type: [{ required: true, message: '试题类型不能为空', trigger: 'blur' }],
  title: [{ required: true, message: '试题题目 仅在列表显示 试卷内不显示不能为空', trigger: 'blur' }],
  question: [{ required: true, message: '题目不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const testTypeList = ref<TestTypeVO[]>([])
const getTestTypeList = async () => {
  const res = await TestTypeApi.getTestTypeList({})
  testTypeList.value = handleTree(res, 'id', 'pid')
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  getTestTypeList()
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TestApi.getTest(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/**
* 添加选项
*
* 将一个新的选项添加到表单数据中，选项的key由选项的长度转换为字母表示，value为空字符串。
*/
const handleAddOption = () => {
  formData.value.options.push({ key: indexToLetter(formData.value.options.length), value: '' })
}
const handleRemoveOption = (index: number) => {
  formData.value.options.splice(index, 1)
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = cloneDeep(formData.value as unknown as TestVO)
    data.typeClassification = data.typeClassification?.join(',')
    data.options=JSON.stringify(data.options)
    if (formType.value === 'create') {
      await TestApi.createTest(data)
      message.success(t('common.createSuccess'))
    } else {
      await TestApi.updateTest(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    type: undefined,
    title: undefined,
    libraryid: undefined,
    question: undefined,
    qimage: undefined,
    qaudio: undefined,
    aType: undefined,
    options: [{ key: indexToLetter(0), value: '' }],
    rightkey: undefined,
    analysis: undefined,
    aimage: undefined,
    anum: undefined,
    rnum: undefined,
    level: undefined,
    qvideo: undefined,
    analysisAudio: undefined,
    knowledge: undefined,
    typeClassification: [],
    qYear: undefined,
    pid: undefined,
    sonStatus: undefined,
    sonSimple: undefined
  }
  formRef.value?.resetFields()
}
</script>